<template>
    <div class="head-upload">
        <el-upload
            class="avatar-uploader"
            :action="action"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload">
            <img v-if="imageUrl" :src="tempAvatar === 'insert' ? imageUrl = '' :imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
    </div>
</template>

<script>
export default {
    name:'headUpload',
    props:['action','uAvatar','tempAvatar'],
    data() 
    {
        return {
            imageUrl: '',
        };
    },
    mounted() 
    {
        // console.log('this.uAvatar',this.uAvatar);
        if(this.uAvatar === ''){}
        else
        this.imageUrl = this.uAvatar //接收初始头像
    },
    methods: 
    {
        handleAvatarSuccess(res, file) 
        {
            this.imageUrl = URL.createObjectURL(file.raw);
            this.$emit('headImgUrl',res)
            console.log(res);
        },
        beforeAvatarUpload(file) 
        {
            const isJPG = file.type === 'image/jpeg';
            const isLt2M = file.size / 1024 / 1024 < 2;

            if (!isJPG) 
            {
                alert('上传的头像只能是JPG格式!');
            }
            if (!isLt2M) 
            {
                alert('上传头像图片大小不能超过 2MB!');
            }
            return isJPG && isLt2M;
        },
        handleImgUrl(val)
        {
            this.imageUrl = val
        }
    }
}
</script>

<style lang="less" scoped>
    .head-upload
    {
        padding: 20px 0;
    }
    .avatar-uploader .el-upload 
    {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
    }
    .avatar-uploader .el-upload:hover 
    {
        border-color: #409EFF;
    }
    .avatar-uploader-icon 
    {
        font-size: 28px;
        color: #8c939d;
        width: 178px;
        height: 178px;
        line-height: 178px;
        border: 1px dashed #ced5dd;
        border-radius: 50%;
        text-align: center;
    }
    .avatar 
    {
        width: 178px;
        height: 178px;
        border-radius: 50%;
        border: 1px dashed #ced5dd;
        display: block;
    }
</style>